package com.wx.pay.utils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2021/7/13 22:21
 */
public class WeiXinPayUtil
{

    private static final String PREFIX_XML = "<xml>";
    private static final String SUFFIX_XML = "</xml>";

    private static final String PREFIX_CDATA = "<![CDATA[";

    private static final String SUFFIX_CDATA = "]]>";

    /**
     * 微信回调参数解析
     *
     * @param request
     * @return
     */
    public static String getPostStr(HttpServletRequest request)
    {
        StringBuffer sb = new StringBuffer();
        try
        {
            ServletInputStream is = request.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String s = "";

            while ((s = br.readLine()) != null)
            {
                sb.append(s);
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        String xml = sb.toString(); //次即为接收到微信端发送过来的xml数据
        return xml;

    }

    /**
     * 转化成xml, 单层无嵌套
     *
     * @param
     * @param isAddCDATA
     * @return
     */
    public String mapToXml(Map<String, String> parm, boolean isAddCDATA)
    {
        StringBuilder builder = new StringBuilder(PREFIX_XML);
        if (null != parm)
        {
            for (Map.Entry<String, String> entry : parm.entrySet())
            {
                builder.append("<").append(entry.getKey()).append(">");
                if (isAddCDATA)
                {
                    builder.append(PREFIX_CDATA);
                    if (null != entry.getValue())
                    {
                        builder.append(entry.getValue());
                    }
                    builder.append(SUFFIX_CDATA);
                } else
                {
                    if (null != entry.getValue())
                    {
                        builder.append(entry.getValue());
                    }
                }
                builder.append("</").append(entry.getKey()).append(">");
            }
        }
        return builder.append(SUFFIX_XML).toString();
    }
}

